<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>活动管理</el-breadcrumb-item>
      <el-breadcrumb-item>活动列表</el-breadcrumb-item>
      <el-breadcrumb-item>活动详情</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="showAddCateDialog"
            >添加分类</el-button
          >
        </el-col>
      </el-row>
      <!-- 表格 -->
      <tree-table
        class="terrtable"
        :data="catelist"
        :columns="columns"
        :show-index="true"
        :expand-type="false"
        :selection-type="false"
        border
      >
        <!-- 是否有效 -->
        <template slot="isok" slot-scope="scope">
          <i
            class="el-icon-check"
            v-if="scope.row.cat_deleted"
            style="color: lightgreen"
          ></i>
          <i class="el-icon-close" v-else style="color: red"></i>
        </template>
        <!-- 排序 -->
        <template slot="order" slot-scope="scope">
          <el-tag size="mini" v-if="scope.row.cat_level == 0">一级</el-tag>
          <el-tag
            size="mini"
            type="success"
            v-else-if="scope.row.cat_level == 1"
            >二级</el-tag
          >
          <el-tag size="mini" type="warning" v-else>三级</el-tag>
        </template>
        <template slot="opt" slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-edit"
            @click="showEditDialog(scope.row.cat_id)"
            >编辑</el-button
          >
          <el-button
            type="danger"
            size="mini"
            icon="el-icon-delete"
            @click="removeCateById(scope.row.cat_id)"
            >删除</el-button
          >
        </template>
      </tree-table>
    </el-card>
    <!-- 添加分类的对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="addCateDialogVisible"
      width="50%"
      @close="addCateDialogClosed"
    >
      <el-form
        :model="addCateForm"
        :rules="addCateFormRules"
        ref="addCateFormRef"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <!--
                 options用来指定数据源
                 props用来指定配置对象
             -->
          <el-cascader
            expand-trigger="hover"
            v-model="selectedOptions"
            :options="parentCateList"
            :props="expandTrigger"
            @change="parentCateChanged"
            clearable
          ></el-cascader>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="addCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改分类的对话框 -->
    <el-dialog
      title="修改分类"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <el-form
        :model="editFrom"
        :rules="editFromRules"
        ref="editFromRef"
        label-width="80px"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editFrom.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCate">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryInfo.pagenum"
      :page-sizes="[3, 5, 10, 15]"
      :page-size="queryInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>
  </div>
</template>
<script>
export default {
  data() {
    return {
       options: {
        title: {
          text: "用户来源",
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross",
            label: {
              backgroundColor: "#E9EEF3",
            },
          },
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: [
          {
            boundaryGap: false,
          },
        ],
        yAxis: [
          {
            type: "value",
          },
        ],
      },
      catelist: [], //商品分类数据列表，默认为空
      queryInfo: {
        //查询条件
        type: 3,
        pagenum: 1,
        pagesize: 5,
      },
      total: 0, //数据总数
      columns: [
        {
          label: "分类名称",
          prop: "cat_name",
        },
        {
          label: "是否有效",
          type: "template", //将当前列定义为模板列
          template: "isok", //表示当前列的模板名称
        },
        {
          label: "排序",
          type: "template", //将当前列定义为模板列
          template: "order", //表示当前列的模板名称
        },
        {
          label: "操作",
          type: "template", //将当前列定义为模板列
          template: "opt", //表示当前列的模板名称
        },
      ],
      //控制添加分类对话框的显示与隐藏
      addCateDialogVisible: false,
      //添加分类的表单数据对象
      addCateForm: {
        //将要添加的分类名称
        cat_name: "",
        //父级分类的Id
        cat_pid: 0,
        //分类的等级，默认要添加的是一级分类
        cat_level: 0,
      },
      //父级分类的列表
      parentCateList: [],
      //添加分类表单的验证规则对象
      addCateFormRules: {
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
        ],
      },
      //指定级联选择器的配置对象
      expandTrigger: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      //选中的父级分类的Id数组
      selectedOptions: [],
      editDialogVisible: false, //控制分类修改的显示和隐藏
      //修改查询到的用户对象
      editFrom: {},
      //修改分类校验规则
      editFromRules: {
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
        ],
      },
     
    };
  },
  created() {
    this.getCateList();
  },

  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get("categories", {
        params: this.queryInfo,
      });
      if (res.meta.status !== 200) {
        return this.$message.error("获取商品分类失败！");
      }
      //将数据传给catelist
      this.catelist = res.data.result;
      //获取总记录条数
      this.total = res.data.total;
    },
    //监听pagesize改变
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getCateList();
    },
    //监听pagenum改变
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage;
      this.getCateList();
    },
    //点击按钮，弹出添加分类对话框
    showAddCateDialog() {
      //获取父级分类的数据列表
      this.getParentCateList();
      this.addCateDialogVisible = true;
    },
    //获取父级分类的数据列表
    async getParentCateList() {
      const { data: res } = await this.$http.get("categories", {
        params: { type: 2 },
      });
      if (res.meta.status !== 200) {
        return this.res.$message.error("获取父级分类失败!");
      }
      
      this.parentCateList = res.data;
    },
    //选择项发生变化触发这个函数
    parentCateChanged() {

      //如果selectedOptions数组中的length大于0，证明选中了父级分类
      //反之则说明没有选中任何父级分类
      if (this.selectedOptions.length > 0) {
        //父级分类的Id
        this.addCateForm.cat_pid = this.selectedOptions[
          this.selectedOptions.length - 1
        ];
        //为当前分类的等级赋值
        this.addCateForm.cat_level = this.selectedOptions.length;
        return;
      } else {
        //父级分类的Id
        (this.addCateForm.cat_pid = 0),
          //为当前分类的等级赋值
          (this.addCateForm.cat_level = 0);
      }
    },
    //点击按钮，添加新的分类
    addCate() {
      //表单预验证
      this.$refs.addCateFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post(
          "categories",
          this.addCateForm
        );
        if (res.meta.status != 201) {
          return this.$message.error("添加分类失败!");
        }
        this.$message.success("添加用户成功!");
        //关闭添加分类对话框
        (this.addCateDialogVisible = false),
          //刷新页面
          this.getCateList();
      });
    },
    //监听对话框的关闭事件，重置表单数据
    addCateDialogClosed() {
      this.$refs.addCateFormRef.resetFields();
      this.selectedOptions = [];
      this.addCateForm.cat_pid = 0;
      this.addCateForm.cat_level = 0;
    },
    //展示修改分类的对话框
    async showEditDialog(id) {
      const { data: res } = await this.$http.get("categories/" + id);
      if (res.meta.status != 200) {
        return tihs.$message.error("查询分类信息失败!");
      }
      this.editFrom = res.data;
      this.editDialogVisible = true;
    },
    //清空分类修改对话框的关闭事件
    editDialogClosed() {
      this.$refs.editFromRef.resetFields();
    },
    //修改分类信息提交
    editCate() {
      this.$refs.editFromRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          "categories/" + this.editFrom.cat_id,
          { cat_name: this.editFrom.cat_name }
        );
        if (res.meta.status != 200) {
          return this.$message.error("修改分类名称失败！");
        }
        this.$message.success("修改分类名称成功！");
        this.editDialogVisible = false;
        //刷新页面
        this.getCateList();
      });
    },
    //删除角色
    async removeCateById(id) {
      //弹窗询问用户是否删除数据
      const confirmResult =await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirmResult !== "confirm") {
        this.$message.info("已取消删除");
        return;
      }
      const { data: res } = await this.$http.delete("categories/" + id);
      if (res.meta.status !== 200) {
        return this.$message.error("删除失败!");
      }
      this.$message.success("删除成功!");
      this.getCateList();
    },
  },
};
</script>
<style lang="less" scoped>
.terrtable {
  margin-top: 20px;
}
.el-cascader {
  width: 100%;
}
</style>